package com.aggregate.pay.ebcpay.support;

import java.util.Base64;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aggregate.pay.ebcpay.support.utils.HEX;
import com.aggregate.pay.ebcpay.support.utils.MD5;
import com.aggregate.pay.ebcpay.support.utils.RSA;

/**
 * 银盈通代付接口签名工具类
 * @author Moyq5
 * @date 2019年3月14日
 */
public class Tool {
	
	private static Logger log = LoggerFactory.getLogger(Tool.class);
	
	public static boolean verify(String data, String sign, String key) {
		log.debug("银盈通->验签：{}", sign);
		log.debug("银盈通->验签内容：{}", data);
		try {
			byte[] bytes = RSA.decrypt(Base64.getDecoder().decode(sign), Base64.getDecoder().decode(key));
			return HEX.toHexString(MD5.encrypt(data.getBytes("UTF-8"))).equalsIgnoreCase(new String(bytes, "UTF-8"));
		} catch (Exception e) {
			log.error("银盈通->验签异常", e);
		}
		return false;
	}
	
	public static String sign(String sign, String key) {
		log.debug("银盈通->签名内容：{}", sign);
		try {
			sign = Base64.getEncoder().encodeToString(RSA.sign(HEX.toHexString(MD5.encrypt(sign.getBytes("UTF-8"))).toUpperCase().getBytes("UTF-8"), Base64.getDecoder().decode(key)));
		} catch (Exception e) {
			log.error("银盈通->签名异常", e);
		}
		log.debug("银盈通->签名值：{}", sign);
		return sign;
	}
	
}